
#include <QProgressBar>
#include <QPushButton>
#include "tasklist.h"
#include "taskhub.h"
#include "log.h"

using namespace Wishmaster;
TaskList::TaskList(Wishmaster::Taskhub* hub, QWidget* parent) : QTreeWidget(parent),
	m_hub(hub)
{
	connect(m_hub, SIGNAL(taskProgress(int, int)), this, SLOT(taskProgress(int, int)));
	connect(m_hub, SIGNAL(taskDone(TaskPtr)), this, SLOT(taskDone(TaskPtr)));
	setColumnCount(3);
	QStringList header;
	header.append(tr("Task"));
	header.append(tr("Progress"));
	header.append("");
	setHeaderLabels(header);
	refill();
}

TaskList::~TaskList()
{
}

void TaskList::taskProgress(int id, int percentage)
{
	for(int i = 0; i < topLevelItemCount(); i++)
	{
		QTreeWidgetItem* item = topLevelItem(i);
		if(item->data(0, TaskIdRole) == id)
		{
			if(percentage == 100)
				delete item;
			else
			{
				QProgressBar* bar = qobject_cast<QProgressBar*>(itemWidget(item, 1));
				if(bar)
					bar->setValue(percentage);
			}
			return;
		}
	}
	// No item was found, but we don't need to add it if it is already done
	if(percentage != 100)
	{
		Wishmaster::TaskPtr task = m_hub->taskById(id);
		if(task)
			addTask(task);
	}
}

void TaskList::taskDone(TaskPtr task)
{
	for(int i = 0; i < topLevelItemCount(); i++)
	{
		QTreeWidgetItem* item = topLevelItem(i);
		if(item->data(0, TaskIdRole) == task->id())
		{
			delete item;
			return;
		}
	}
}

void TaskList::refill()
{
	clear();
	for(int index = 0; index < m_hub->taskCount(); index++)
	{
		Wishmaster::TaskPtr task = m_hub->taskByIndex(index);
		if(!task.isNull() && task->percentage() < 100)
			addTask(task);
	}
}

void TaskList::addTask(Wishmaster::TaskPtr task)
{
	QTreeWidgetItem* item = new QTreeWidgetItem();
	item->setText(0, task->message());
	QProgressBar* bar = new QProgressBar();
	bar->setValue(0);
	bar->setMaximum(100);
	item->setData(0, TaskIdRole, task->id());
	addTopLevelItem(item);
	setItemWidget(item, 1, bar);
	resizeColumnToContents(0);
	setColumnWidth(1, 200);
	QPushButton* btn = new QPushButton(QIcon(":/wishmaster/images/close.png"), "");
	btn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
	btn->setFixedWidth(40);
	btn->setProperty("task_id", task->id());
	connect(btn, SIGNAL(clicked()), this, SLOT(cancel()));
	setItemWidget(item, 2, btn);
}

void TaskList::cancel()
{
	if(!sender())
		return;
	int task_id = sender()->property("task_id").toInt();
	if(task_id)
		m_hub->cancelTask(task_id);
	for(int i = 0; i < topLevelItemCount(); i++)
	{
		QTreeWidgetItem* item = topLevelItem(i);
		if(item->data(0, TaskIdRole).toInt() == task_id)
			delete item;
	}
}

